package parserUML;

import java.util.*;
import java.io.*;

public class FolderParser extends Constants{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8832522227584138817L;

	public static ArrayList<ClassObject> analyse(String rep) throws Exception{
		
		java.io.InputStream input;
		ArrayList<ClassObject> res = new ArrayList<ClassObject>();
		ArrayList<String> javaFiles = scanDirForJavaFiles(rep);
		JavaParser parser;
		input = new java.io.FileInputStream(javaFiles.get(0)+".java");
		parser = new JavaParser(input);
		System.out.println("0  :  "+javaFiles.get(0));
		parser.analyse();
		for(ClassObject classe : JavaParser.classes){
			res.add(classe);
		}
		for(int i=1; i<javaFiles.size(); i++){
			System.out.println(i+"  :  "+javaFiles.get(i));
			input = new java.io.FileInputStream(javaFiles.get(i)+".java");
			parser.ReInit(input);
			//parser = new JavaParser(input);
			parser.analyse();
			for(ClassObject classe : JavaParser.classes){
				res.add(classe);
			}
		}
		return res;
	}
	private static ArrayList<String> scanDirForJavaFiles ( String theDirectory ) throws IOException {
        
        File currDir = new File ( theDirectory );
        ArrayList<String> finalListFiles = new ArrayList<String>();
        // Return null if not a directory
        if ( currDir.exists() && ! currDir.isDirectory() ){
            return null;
        }
        
        String[] fileList = currDir.list();
        
        for (int i=0; i<fileList.length; i++ ){
            ArrayList<String> temp = scanDirForJavaFiles ( theDirectory + File.separator + fileList[i] );
            if ( temp == null){
                // --- Add the path of the current file
            	if(getFileExtension(fileList[i]).equals(".java"))
                	{finalListFiles.add(theDirectory + File.separator + removeFileExtension(fileList[i]));}
            }
            else{
                // --- Add the array list of the current directory
            	for(String javaFile : temp){
            		finalListFiles.add(javaFile);
            	}
            }
        }
    
        // --- Finally, return the arrayList
        for(String s : finalListFiles){System.out.println(s);}
        return finalListFiles;
	}
	
	private static String getFileExtension(String fileName){
		int point = fileName.lastIndexOf(".");
		if (point == -1) point = 0;
		return fileName.substring(point, fileName.length());
	}
	
	private static String removeFileExtension(String fileName){
		return fileName.substring(0, fileName.lastIndexOf("."));
	}
}
